package cn.com.open.opensaas.scoreservice.controller;

import cn.com.open.opensaas.scoreservice.domain.TestPaperModel.TestPaperContent;
import cn.com.open.opensaas.scoreservice.service.PaperContentService;
import cn.com.open.opensaas.scoreservice.util.BaseControllerUtil;
import cn.com.open.opensaas.scoreservice.util.StringUtil;
import cn.com.open.opensaas.scoreservice.util.WebUtils;
import cn.com.open.opensaas.scoreservice.controller.interceptor.Log;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 试卷判分接口
 */
@Controller
@RequestMapping("/Paper/")
public class PaperJudgeController extends BaseControllerUtil {
    private static final Logger log = LoggerFactory.getLogger(PaperJudgeController.class);

    @Autowired
    private PaperContentService paperContentService;

    /**
     * 试卷判分
     *
     * @param request
     * @param response
     */

    @Log(optType = "试卷判分", optDescription = "为GUID为%s的试卷判分", keyName = "paperId")
    @RequestMapping(value = "{paperId}/Judge", method = RequestMethod.POST)
    public void judge(HttpServletRequest request, HttpServletResponse response, @PathVariable String paperId, @RequestBody Map dataObj) {
        log.info("-----------------------judge start----------------");

        //存储最终返回值
        Map<String, Object> resultMap = new LinkedHashMap<>();

        //获取参数ItemResult(学生答案Json)
        Object itemResult = dataObj.get("Items");
        request.setAttribute("Items", itemResult);

        if (StringUtils.isEmpty(itemResult) || paperId == null) {
            WebUtils.writeJudgeErrorMap(-201, "参数不完整", response);
        } else {
            List<Map<String, Object>> questionList = (List<Map<String, Object>>) itemResult;
            if (questionList.isEmpty()) {
                WebUtils.writeJudgeErrorMap(-201, "参数不完整", response);
            } else {
                TestPaperContent paperContent = paperContentService.findTestPaperById(paperId);
                if (StringUtils.isEmpty(paperContent)) {
                    WebUtils.writeJudgeErrorMap(-214, "试卷不存在", response);
                }
                String contentJson = paperContent.getContentJson().replace("\\","");
                if (StringUtil.isEmpty(contentJson)) {
                    WebUtils.writeJudgeErrorMap(-215, "试卷内容不存在", response);
                }
                Map<String, Object> paperContentMap = JSON.parseObject(contentJson);
                resultMap = paperContentService.judge(questionList, paperContentMap);
            }
        }

        WebUtils.writeJsonToMap(response, resultMap);
    }
}